package cn.safekeeper.guide.admin.controller.system.dict;

import cn.safekeeper.guide.admin.constant.MsgObj;
import cn.safekeeper.guide.admin.constant.UserConstants;
import cn.safekeeper.guide.admin.controller.BaseController;
import cn.safekeeper.guide.admin.domain.entity.SysDictType;
import cn.safekeeper.guide.admin.domain.page.TableDataInfo;
import cn.safekeeper.guide.admin.service.ISysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 数据字典信息
 */
@RestController
@RequestMapping("/system/dict/type")
public class SysDictTypeController extends BaseController {
    @Autowired
    private ISysDictTypeService dictTypeService;

    @GetMapping("/list")
    public TableDataInfo list(SysDictType dictType) {
        startPage();
        List<SysDictType> list = dictTypeService.selectDictTypeList(dictType);
        return getDataTable(list);
    }


    /**
     * 查询字典类型详细
     */
    @GetMapping("/query")
    public MsgObj getInfo(Long dictId) {
        return MsgObj.success(dictTypeService.selectDictTypeById(dictId));
    }

    /**
     * 新增字典类型
     */
    @PostMapping("/add")
    public MsgObj add(@Validated @RequestBody SysDictType dict) {
        if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
            return MsgObj.error("新增字典'" + dict.getDictName() + "'失败，字典类型已存在");
        }
        dict.setCreateBy(getUsername());
        return toAjax(dictTypeService.insertDictType(dict));
    }

    /**
     * 修改字典类型
     */
    @PutMapping("/edit")
    public MsgObj edit(@Validated @RequestBody SysDictType dict) {
        if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) {
            return MsgObj.error("修改字典'" + dict.getDictName() + "'失败，字典类型已存在");
        }
        dict.setUpdateBy(getUsername());
        return toAjax(dictTypeService.updateDictType(dict));
    }

    /**
     * 删除字典类型
     */
    @DeleteMapping("/remove")
    public MsgObj remove(Long[] dictIds) {
        dictTypeService.deleteDictTypeByIds(dictIds);
        return success();
    }

    /**
     * 刷新字典缓存
     */
    @DeleteMapping("/refreshCache")
    public MsgObj refreshCache() {
        dictTypeService.resetDictCache();
        return MsgObj.success();
    }

    /**
     * 获取字典选择框列表
     */
    @GetMapping("/optionselect")
    public MsgObj optionselect() {
        List<SysDictType> dictTypes = dictTypeService.selectDictTypeAll();
        return MsgObj.success(dictTypes);
    }
}
